package 网络编程2套接字.UDP数据报套接字编程.翻译程序;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

//客户端要做一个很重要的事情,就是和用户进行交互.
//不同的场景下,和用户的交互的方式也是不同的.
//当前咱们写的echo和dict其实都是按照命令行的方式和用户进行交互的.
public class UdpDictClient {
    private DatagramSocket socket = null;
    private String serverIP;
    private int serverPort;

    public UdpDictClient(String serverIP,int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        this.socket = new DatagramSocket();
    }
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while(true){
            //1.读取输入的数据
            System.out.println("->");
            String request = scanner.nextLine();
            if(request.equals("exit")){
                System.out.println("goodbye!");
                return;
            }
            //2.构造请求并发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);//发送给服务器
            //3.从服务器读取响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);//从服务器读取响应,然后将内容写入responsePacket
            //然后将内容存到字符串中去
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());

            //4.将数据显示给用户
            String log = String.format("req: %s; resp: %s",request,response);
            System.out.println(log);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpDictClient client = new UdpDictClient("127.0.0.1",9090);
        client.start();
    }
}
